package com.beikai.demo01.io;

import java.io.*;

/**
 * Created with IntelliJ IDEA.
 *
 * @author : hanbeikai
 * Date: 2021/5/5 2:29 下午
 * Description: 测试io
 */
public class IoDemo2 {
    public static void main(String[] args) throws IOException {
        File file = new File("/Users/hanbeikai/Desktop/test.txt");
        File file2 = new File("/Users/hanbeikai/Desktop/test2.txt");
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < 3000000; i++) {
            sb.append("abcdefghigklmnopqrstuvwsyz");
        }
        byte[] bytes = sb.toString().getBytes();

        long start = System.currentTimeMillis();
        write(file, bytes);
        long end = System.currentTimeMillis();

        long start2 = System.currentTimeMillis();
        bufferedWrite(file2, bytes);
        long end2 = System.currentTimeMillis();

        System.out.println("普通字节流耗时：" + (end - start) + " ms");
        System.out.println("缓冲字节流耗时：" + (end2 - start2) + " ms");

    }

    // 普通字节流
    public static void write(File file, byte[] bytes) throws IOException {
        OutputStream os = new FileOutputStream(file);
        int tempStart = 0;
        int len = 1024;
        int all = bytes.length;
        while (tempStart < all){
            int temp = all - tempStart;
            if (temp < len){
                len = temp;
            }
            os.write(bytes, tempStart, len);
            tempStart += len;
        }
        os.close();
    }

    // 缓冲字节流
    public static void bufferedWrite(File file, byte[] bytes) throws IOException {
        BufferedOutputStream bo = new BufferedOutputStream(new FileOutputStream(file));
        int tempStart = 0;
        int len = 1024;
        int all = bytes.length;
        while (tempStart < all){
            int temp = all - tempStart;
            if (temp < len){
                len = temp;
            }
            bo.write(bytes, tempStart, len);
            tempStart += len;
        }
        bo.close();
    }
}
